//
//  RatingControl.swift
//  4-5classWork
//
//  Created by Qingke on 16/4/5.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class RatingControl: UIView {
    //这里的内容都需要用var,因为需要被其他程序员修改和调用，如果是不要修改 需要加一个
    var rating = 0 {
        didSet {
            
            if oldValue != rating {
                print("你的了\(rating)分")
                up()
            }
        }
    }
    var buttons = [UIButton]()  //创建一个放对象的数组，这样可以系列处理
    
    var buttonHeight: CGFloat = 44
    var buttonWidth: CGFloat = 44
    var starNum : Int = 5
    var space: CGFloat = 5
    
    
    let emptyStar = UIImage( named: "emptyStar") //错误标示不一样，方法就不一样，错误是用了下面内容就导致无法显示。用name
    //let emptyStar = UIImage(contentsOfFile: "emptyStar.imagesetr")
    let filledStar = UIImage( named: "filledStar")
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        for i in 0..<starNum {
            print("创建第\(i)个按钮")
            let button = UIButton()
           // button.backgroundColor = UIColor.redColor()
            button.addTarget(self, action: "ratingControlTapped:", forControlEvents: UIControlEvents.TouchDown)
            button.setImage(emptyStar, forState: .Normal)
            button.setImage(filledStar, forState: .Selected)
            button.setImage(filledStar, forState: [.Highlighted,.Selected])
            button.adjustsImageWhenHighlighted = false   //防止选择闪动
            button.tag = (i + 1)
            buttons.append(button)
            addSubview(button)
            
        }
    }
    func ratingControlTapped (button:UIButton) {
        print("点了评分按钮")
        button.selected = true
        rating = button.tag
        
    }
    
    func up () {
        for button in buttons {
            if button.tag <= rating {
                button.selected = true
            } else {
                button.selected = false
            }
        }
    }
    
    override func layoutSubviews() {
        print("layoutSubviews")
        var frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight)    //对于CGRect 所需要的值是CGFloat,虽然它显示有用Int。
        
        for button in buttons {
            button.frame = frame
            frame.origin.x  += buttonWidth + space
        }
        
    }
    
    
    override func intrinsicContentSize() -> CGSize {
        return CGSize(width: (buttonWidth+space) * CGFloat(starNum), height: buttonHeight)
    }
    
 
}
